package com.jianjian.system.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jianjian.model.system.SysUser;
import com.jianjian.model.vo.RouterVo;
import com.jianjian.model.vo.SysUserQueryVo;
import com.jianjian.system.mapper.SysUserMapper;
import com.jianjian.system.service.SysMenuService;
import com.jianjian.system.service.SysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author cool
 * @since 2022-11-06
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysMenuService sysMenuService;

    @Override
    public IPage<SysUser> selectPage(Page<SysUser> pageParam, SysUserQueryVo sysUserQueryVo) {

        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();

        if (!StringUtils.isEmpty(sysUserQueryVo.getKeyword())){
            wrapper.like("username",sysUserQueryVo.getKeyword())
            .or().like("name",sysUserQueryVo.getKeyword())
            .or().like("phone",sysUserQueryVo.getKeyword());
        }
        if (!StringUtils.isEmpty(sysUserQueryVo.getCreateTimeBegin())){
            wrapper.and(w->w.ge("create_time",sysUserQueryVo.getCreateTimeBegin()));
        }
        if (!StringUtils.isEmpty(sysUserQueryVo.getCreateTimeEnd())){
            wrapper.and(w->w.le("create_time ",sysUserQueryVo.getCreateTimeEnd()));
        }
        wrapper.orderByDesc("id");

        return baseMapper.selectPage(pageParam,wrapper);
    }

    //根据用户名查询id
    @Override
    public SysUser getUserByUsername(String username) {
        return   this.getOne(new QueryWrapper<SysUser>().eq("username",username));
    }

    //根据用户名称获取用户信息（基本信息 和 菜单权限 和 按钮权限）
    @Override
    public Map<String, Object> getUserInfo(String username) {
        Map<String, Object> map = new HashMap<>();
        map.put("roles","[admin]");
        map.put("name",username);
        map.put("avatar","https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");

        //根据username用户名查询用户的基本信息
        SysUser sysUser = this.getUserByUsername(username);

        //根据用户id查询菜单权限值
        List<RouterVo> routerVoList=  sysMenuService.getMenuByUserId(sysUser.getId());
        map.put("routers", routerVoList);//菜单权限数据

        //根据用户id查询按钮权限值
        List<String> buttonList =  sysMenuService.getButtonByUserId(sysUser.getId());
        map.put("buttons", buttonList);//按钮权限数据

        return map;
    }
}
